import requests
import io
import traceback
import pymysql
import json
from PIL import Image, ImageDraw, ImageFont
from pyquery import PyQuery as pq

def get_image_list1(url):
	r = requests.get(url)
	doc = pq(r.text)
	url_list = doc('.first-image img').items()
	img_list = []
	for img in url_list:
		img_response = requests.get('https:%s' % img.attr('src'))
		try :
			img_list.append(Image.open(io.BytesIO(img_response.content)))
		except:
			print("img error")
	img_list.append("轮播图结束")
	url_list = doc('.detail-tab .section img').items()
	for img in url_list:
		img_response = requests.get('https:%s' % img.attr('src'))
		try :
			img_list.append(Image.open(io.BytesIO(img_response.content)))
		except:
			print("img error")
	return img_list


def get_image_list2(url):
	if (url.startswith("https://haohuo.jinritemai.com/views/product/item.html")):
		url = url.replace("https://haohuo.jinritemai.com/views/product/item.html", "https://ec.snssdk.com/product/lubanajaxstaticitem")
	elif (url.startswith("https://haohuo.jinritemai.com/views/product/item2.html")):
		url = url.replace("https://haohuo.jinritemai.com/views/product/item2.html", "https://ec.snssdk.com/product/lubanajaxstaticitem")
	elif (url.startswith("https://haohuo.jinritemai.com/views/product/item2/")):
		url = url.replace("https://haohuo.jinritemai.com/views/product/item2/", "https://ec.snssdk.com/product/lubanajaxstaticitem")
	elif (url.startswith("https://haohuo.jinritemai.com/views/product/item2")):
		url = url.replace("https://haohuo.jinritemai.com/views/product/item2", "https://ec.snssdk.com/product/lubanajaxstaticitem")
	else:
		url = url.replace("https://haohuo.jinritemai.com/views/product/item", "https://ec.snssdk.com/product/lubanajaxstaticitem")
	print(url)
	r = requests.get(url)
	resp = r.json()
	data = resp.get('data')
	url_list = data.get('img_list')
	img_list = []
	try:
		for img in url_list:
			img_response = requests.get(img)
			try :
				img_list.append(Image.open(io.BytesIO(img_response.content)))
			except:
				print("img error")
		img_list.append("轮播图结束")
		desc = data.get('description')
		doc = pq(desc)
		url_list = doc('img').items()
		for img in url_list:
			img_response = requests.get(img.attr('src'))
			try :
				img_list.append(Image.open(io.BytesIO(img_response.content)))
			except:
				print("img error")
	except: 
		print("商品已下架")
	return img_list

def splice_img(img_list, img_name, ft):
	print(img_list)
	try:
		sum_height = 0
		width = 0
		for im in img_list:
			if isinstance(im, str):
				sum_height += 40
			else:
				if im.size[0] > width:
					width = im.size[0]
				sum_height += (im.size[1] + 40)
		result = Image.new('RGB', (width, sum_height))
		draw_table = ImageDraw.Draw(im=result)
		# 拼接
		top = 0
		j = 1
		for i, im in enumerate(img_list):
		   # mew_im = im.resize(ims_size[i], Image.ANTIALIAS)  # 等比缩放
			if isinstance(im, str):
				draw_table.text((20, top + 5), im, font=ft)
				top += 40
			else:
				result.paste(im, box=(0, top))
				top += im.size[1]
				draw_table.text((20, top + 5), '第%d张' % j, font=ft)
				j += 1
				top += 40
		# 保存
		result.save('Image/img3/%s.jpg' % img_name)
	except Exception as e:
		msg = traceback.format_exc()
		print("paste error %s" % msg)

if __name__ == '__main__':
	db = pymysql.connect(host='localhost', user='root', password='Root123', port=3306, db='springboot')
	cursor = db.cursor()
			
	sql = """
			SELECT
	page_id,
	page_url
FROM
	sheet1 where page_url != '' order by A desc LIMIT 20000, 5000
		"""
	cursor.execute(sql)
	# res = cursor.fetchall()
	row = cursor.fetchone()
	ft = ImageFont.truetype("/mnt/c/WINDOWS/Fonts/simhei.ttf", 30)
	while row:
		print(row)
		try:
			img_name = row[0]
			img_url = row[1]
			row = cursor.fetchone()
			img_list = []
			if (img_url.startswith("https://haohuo.jinritemai.com")):
				img_list = get_image_list2(img_url)
			else:
				img_list = get_image_list1(img_url)
			if img_list:
				splice_img(img_list, img_name, ft)
		except Exception as e:
			msg = traceback.format_exc()
			print("paste error %s" % msg)